<?php
// +----------------------------------------------------------------------
// | 07FLYCRM [基于ThinkPHP5.0开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2021 http://www.07fly.xyz
// +----------------------------------------------------------------------
// | Professional because of focus  Persevering because of happiness
// +----------------------------------------------------------------------
// | Author: 开发人生 <goodkfrs@qq.com>
// +----------------------------------------------------------------------


namespace app\admin\model;

use app\common\model\ModelBase;
use think\Loader;

/**
 * Admin基础模型
 */
class AdminBase extends ModelBase
{
    /**
     * 重写获取器 兼容 模型|逻辑|验证|服务 层实例获取
     */
    public function __get($name)
    {
        $layer = $this->getLayerPrefix($name);
        if (false === $layer) {
            return parent::__get($name);
        }

        $model = sr($name, $layer);

        if (LAYER_VALIDATE_NAME == $layer) {
            // 层级查找：当前模块 → admin模块 → common模块
            try {
                // 首先尝试当前模块
                return Loader::validate($model, $layer, false, request()->module());
            } catch (\Exception $e) {
                try {
                    // 当前模块不存在，尝试admin模块
                    return Loader::validate($model, $layer, false, 'admin');
                } catch (\Exception $e) {
                    // plat模块也不存在，尝试common模块
                    return Loader::validate($model, $layer, false, 'common');
                }
            }
        } else {
            // 层级查找：当前模块 → admin模块 → common模块
            try {
                // 首先尝试当前模块
                return Loader::model($model, $layer, false, request()->module());
            } catch (\Exception $e) {
                try {
                    // 当前模块不存在，尝试admin模块
                    return Loader::model($model, $layer, false, 'admin');
                } catch (\Exception $e) {
                    // plat模块也不存在，尝试common模块
                    return Loader::model($model, $layer, false, 'common');
                }
            }
        }
    }

    /**
     * 获取层前缀
     */
    public function getLayerPrefix($name)
    {
        $layer = false;
        $layer_array = [LAYER_MODEL_NAME, LAYER_LOGIC_NAME, LAYER_VALIDATE_NAME, LAYER_SERVICE_NAME];
        foreach ($layer_array as $v) {
            if (str_prefix($name, $v)) {
                $layer = $v;
                break;
            }
        }
        return $layer;
    }
}
